package com.telit.web.service;

import com.telit.web.dto.AppVideoDTO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;


/**
 * @Auther amy
 * @Describe
 */
@Service
public class AliVideoService {

    @Value("${aliyun.video.appId}")
    private String appId;

    @Value("${aliyun.video.appKey}")
    private String appKey;

    @Value("${aliyun.video.gslb}")
    private String gslb;

    /**
     * 创建阿里云音视频所需token
     *
     * @param timestamp
     * @param userId
     * @param channelId
     *
     * @throws NoSuchAlgorithmException
     */
    public String createToken(String timestamp, String userId, String channelId, String nonce)
            throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        digest.update(appId.getBytes());
        digest.update(appKey.getBytes());
        digest.update(channelId.getBytes());

        digest.update(userId.getBytes());
        digest.update(nonce.getBytes());
        digest.update(timestamp.getBytes());
        String token = DatatypeConverter.printHexBinary(digest.digest()).toLowerCase();
        return token;
    }

    /**
     * 封装发起人的音视频信息
     *
     * @return
     */
    public AppVideoDTO getAppSimpleTokenInfo(String timestamp, String userId, String channelId, String nonce)
            throws NoSuchAlgorithmException {
        AppVideoDTO appVideoDTO = new AppVideoDTO();
        appVideoDTO.setAppId(appId);
        appVideoDTO.setAppKey(appKey);
        appVideoDTO.setChannelId(channelId);
        appVideoDTO.setGslb(gslb);
        appVideoDTO.setPushDate(new Date());
        appVideoDTO.setTimestamp(timestamp);
        appVideoDTO.setUserId(userId);
        appVideoDTO.setNonce(nonce);
        appVideoDTO.setToken(createToken(timestamp, userId, channelId, nonce));
        return appVideoDTO;
    }

}
